
#include "sndatainterface.h"
#include "ui_sndatainterface.h"
#include "nodepage.h"

#include <QInputDialog>
#include <QColorDialog>
#include <QString>
#include <QDebug>

#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QListIterator>
#include <QSettings>
#include <QTime>
#include <QDate>
#include <QTimer>




QList<Node *> NodeList;
QList<NodePage *> tabPage;

QString directory;
QSettings *settings;
QCustomPlot *timeGraph;
QTimer timer;
int nodeCount;
char fBuffer[299];
int graphIndex = 0;


union frame{
    char buffer[294];
    struct{
        quint16 nodeID;
        quint32 time;
        quint16 adcChannel[16];
        quint16 line[128];
    }d;
};

frame curFrame;

struct graphStruct{
    QCPGraph *graph;
    int NodeIndex;
    int adcCh;
    QColor plotColor;
};

QList<graphStruct *> graphList;

SNDataInterface::SNDataInterface(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SNDataInterface)
{
    ui->setupUi(this);

    timeGraph = ui->TimeGraphPlot;

//    timeGraph->addGraph();
//    timeGraph->graph(0)->setPen(QPen(Qt::blue));
//    timeGraph->graph(0)->setAntialiasedFill(false);

    timeGraph->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    timeGraph->xAxis->setDateTimeFormat("hh:mm:ss.zzz");
    timeGraph->xAxis->setAutoTickStep(false);
    timeGraph->xAxis->setTickStep(2);
    timeGraph->axisRect()->setupFullAxesBox();

    timeGraph->yAxis->setRange(-100,4100);

    // make left and bottom axes transfer their ranges to right and top axes:
    connect(timeGraph->xAxis, SIGNAL(rangeChanged(QCPRange)), timeGraph->xAxis2, SLOT(setRange(QCPRange)));
    connect(timeGraph->yAxis, SIGNAL(rangeChanged(QCPRange)), timeGraph->yAxis2, SLOT(setRange(QCPRange)));

    connect(&timer, SIGNAL(timeout()), this, SLOT(plotTimeData()));
}

SNDataInterface::~SNDataInterface()
{
    delete ui;
}


/*
 *
 * Read the saved setting from SASNet Raw Log
 *
 *
*/
void SNDataInterface::readSettings()
{
    QCoreApplication::setOrganizationName("RDDC Valcartier");
    QCoreApplication::setApplicationName("SN Logger");

    settings = new QSettings(directory + "/SNlogger.ini", QSettings::IniFormat);
    Node *newNode = new Node();
    QFile *tFile;
    QString filename;

    nodeCount = settings->beginReadArray("nodesInfo");

    for(int i = 0; i< nodeCount; ++i)
    {
        settings->setArrayIndex(i);

        newNode->nodeIP = settings->value("nodeIP").toString();
        newNode->nodeName = settings->value("nodeName").toString();
        newNode->nodeLocLat = settings->value("nodeLocLat").toString();
        newNode->nodeLocLon = settings->value("nodeLocLon").toString();
        newNode->nodeLocN = settings->value("nodeLocN").toFloat();
        newNode->nodeLocE = settings->value("nodeLocE").toFloat();
        filename = newNode->filename = settings->value("filename").toString();

        for(int j=0;j<16;j++)
            newNode->adcChIsPlot[j] = -1; //will contain index to the graph

        NodeList.append(newNode);

        tabPage.append(new NodePage(i, NodeList[i]));

        ui->NodeTab->addTab(tabPage[i], newNode->nodeName);
        connect(tabPage[i],SIGNAL(changeTimeGraphItem(int, int)),this, SLOT(timeGraphComponent(int,int)));

        tFile = &NodeList[i]->logFile;
        tFile->setFileName(filename);
        if(!tFile->open(QIODevice::ReadOnly))
        {
            qDebug() << "Error opening file:" << filename;
        }
    }
    settings->endArray();
}

/*
 *
 *  This button select which directory contains the data to work with
 *
 *
*/

void SNDataInterface::on_OpenDataFileBut_clicked()
{
    directory = QFileDialog::getExistingDirectory(this, tr("Select Replay Directory"),
                                                  "C:/temp/",
                                                  QFileDialog::ShowDirsOnly
                                                  | QFileDialog::DontResolveSymlinks);

    if(directory.isEmpty() || NodeList.size() != 0) // there is no data to read or node list not empty
        return;

    ui->StartBut->setEnabled(true);
    ui->OpenDataFileBut->setEnabled(false);

    readSettings();
}


void SNDataInterface::timeGraphComponent(int pageIndex, int itemIndex)
{
    graphStruct *newGraph = new graphStruct;
    if(NodeList[pageIndex]->adcChIsPlot[itemIndex] == -1){    // add this node / adc channel a graph
        NodeList[pageIndex]->adcChIsPlot[itemIndex] = graphIndex++;
        QColor pageItemColor = QColorDialog::getColor("chose ADC channel plot color");
        pageItemColor.setAlpha(225);
        tabPage[pageIndex]->changePageItemColor(itemIndex, pageItemColor);

        newGraph->NodeIndex = pageIndex;
        newGraph->adcCh = itemIndex;
        newGraph->plotColor = pageItemColor;
        newGraph->graph = timeGraph->addGraph();
        newGraph->graph->setPen(QPen(pageItemColor));
        newGraph->graph->setAntialiasedFill(false);

        graphList.append(newGraph);
    }
    else{
        NodeList[pageIndex]->adcChIsPlot[itemIndex] = -1; //remove association with a graph
        tabPage[pageIndex]->changePageItemColor(itemIndex,Qt::white);
        for(int i=0;i<graphList.size();i++){
            if(graphList[i]->NodeIndex == pageIndex && graphList[i]->adcCh == itemIndex){
                timeGraph->removeGraph(graphList[i]->graph);
                graphList.removeAt(i);
                break; //found graph to remove exit for loop
            }
        }
    }
}


void SNDataInterface::plotTimeData(){
    QFile *in;
    double key, value;
    char ch, tag[6] = "FRAME";
    int cnt = 0;
    for(int i = 0; i< nodeCount; ++i)
    {
        in = &NodeList[i]->logFile;

        // search for the tag "FRAME" indicating begining of a data frame
        while(!in->atEnd() && in->read(&ch,1))
            if(ch == tag[cnt]){
                if(cnt == 4) // tag found
                    break;
                else{
                    cnt++;
                    continue;
                }
            }
            else
                continue; //not reading the tag, go to next

        in->read(curFrame.buffer,294);

        key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;

        for(int node = 0; node < nodeCount; node++){
            for(int i = 0;i< graphList.size();i++)
                if(graphList[i]->NodeIndex == node){ //there is a node where at least a adc channel will be plotted
                    value = (quint16)(qFromLittleEndian(curFrame.d.adcChannel[graphList[i]->adcCh]));
                    graphList[i]->graph->addData(key, value);
                }

        }
        // make key axis range scroll with the data (at a constant range size of 8):
        timeGraph->xAxis->setRange(key+0.2, 8, Qt::AlignRight);
        timeGraph->replot();
    }
}

void SNDataInterface::on_StartBut_clicked()
{
    ui->StartBut->setEnabled(false);
    timer.start(40);
}


